//
//  MKTitleOptionsTrackBar.m
//  MapleKit
//
//  Created by 赵磊 on 2019/7/25.
//

#import "ZLScrollToolBar.h"

@interface ZLScrollToolBar ()

{
    ZLScrollToolBarConfig *_config;
}

///内容视图
@property (nonatomic,weak) UIView *contentView;
///上次点击的按钮
@property (nonatomic,weak) UIButton *lastButton;
///跟踪条
@property (nonatomic,weak) CALayer *trackBar;

@end

@implementation ZLScrollToolBar

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        //ios11 适配
        if (@available(iOS 11.0, *)) {
            self.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            self.scrollIndicatorInsets = self.contentInset;
        }
        self.contentSize = self.bounds.size;
        self.backgroundColor = UIColor.clearColor;
        self.contentView.backgroundColor = UIColor.clearColor;
        self.alwaysBounceVertical = NO;
        self.showsVerticalScrollIndicator = NO;
        self.showsHorizontalScrollIndicator = NO;
    }
    return self;
}
- (void)layoutSubviews {
    [super layoutSubviews];
    
    CGFloat totalButtonWidth = 0;
    for (UIButton *item in self.contentView.subviews) {
        CGFloat width = [item.titleLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:item.titleLabel.font} context:nil].size.width;
        totalButtonWidth += width;
    }
    
    ///未来的总长度
    CGFloat maxWidth = totalButtonWidth + (self.contentView.subviews.count - 1) * self.config.minItemSpace + self.config.edgeSpace * 2;
    
    CGFloat lastX = self.config.edgeSpace;
    CGFloat itemSpace = (self.frame.size.width - totalButtonWidth - self.config.edgeSpace * 2) / (self.contentView.subviews.count - 1);
    for (UIButton *item in self.contentView.subviews) {
        CGFloat width = [item.titleLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:item.titleLabel.font} context:nil].size.width;
        CGRect frame = item.frame;
        if (maxWidth <= self.frame.size.width && self.config.minCountAutoOnCenter) {
            NSInteger index = [self.contentView.subviews indexOfObject:item];
            item.frame = CGRectMake(!index ? lastX : CGRectGetMaxX(self.contentView.subviews[index - 1].frame) + itemSpace, 0, width, self.frame.size.height);
            if (index == self.contentView.subviews.count - 1) {
                lastX = self.frame.size.width;
            }
        }else {
            frame.origin.x = lastX;
            frame.origin.y = 0;
            frame.size.width = width;
            frame.size.height = self.frame.size.height;
            item.frame = frame;
            CGFloat space = self.contentView.subviews.lastObject == item ? item.frame.size.width + self.config.edgeSpace : item.frame.size.width + self.config.minItemSpace;
            lastX += space;
        }
        if (item.selected) {
            CGFloat width = self.config.trackBarBounds.size.width;
            CGFloat height = self.config.trackBarBounds.size.height;
            CGFloat x = CGRectGetMinX(item.frame) + (CGRectGetWidth(item.frame) - width) / 2;
            CGFloat y = self.frame.size.height - self.config.trackBarBottomSpace - height;
            self.trackBar.frame = CGRectMake(x, y, width, height);
        }
    }
    self.contentSize = CGSizeMake(lastX, self.frame.size.height);
}

#pragma mark - Set
- (void)setContentSize:(CGSize)contentSize {
    super.contentSize = contentSize;
    self.contentView.frame = CGRectMake(0, 0, contentSize.width, contentSize.height);
}
- (void)setTitles:(NSArray<NSString *> *)titles {
    if (self.titles.count) {
        return;
    }
    _titles = titles;
    [self createItems];
}
- (void)setSelectIndex:(NSInteger)selectIndex {
    //防越界处理
    if (selectIndex >= self.contentView.subviews.count) {
        return;
    }
    [self itemAction:self.contentView.subviews[selectIndex]];
}
- (void)setConfig:(ZLScrollToolBarConfig *)config {
    _config = config;
    self.trackBar.hidden = !config.showTrackBar;
    if (config.showTrackBar) {
        self.trackBar.backgroundColor = config.trackBarColor.CGColor;
        self.trackBar.cornerRadius = config.trackBarCornerRadius;
        self.trackBar.masksToBounds = YES;
    }
    for (UIButton *item in self.contentView.subviews) {
        [item setTitleColor:config.itemDefaultColor forState:UIControlStateNormal];
        [item setTitleColor:config.itemSelectedColor forState:UIControlStateSelected];
        item.titleLabel.font = item.selected ? config.itemSelectedFont : config.itemDefaultFont;
    }
}

#pragma mark - Lazy
- (UIView *)contentView {
    if (!_contentView) {
        UIView *view = [[UIView alloc] initWithFrame:self.bounds];
        view.backgroundColor = UIColor.whiteColor;
        [self addSubview:view];
        _contentView = view;
    }
    return _contentView;
}
- (CALayer *)trackBar {
    if (!_trackBar) {
        CALayer *layer = [CALayer layer];
        layer.hidden = YES;
        [self.contentView.layer addSublayer:layer];
        _trackBar = layer;
    }
    return _trackBar;
}
- (ZLScrollToolBarConfig *)config {
    if (!_config) {
        _config = [ZLScrollToolBarConfig defaultConfig];
        [self setConfig:_config];
    }
    return _config;
}

#pragma mark - Private
- (void)createItems {
    [self.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (NSInteger index = 0; index < self.titles.count; index++) {
        NSString *title = self.titles[index];
        UIButton *button = [[UIButton alloc] init];
        [button addTarget:self action:@selector(itemAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.contentView addSubview:button];
        [button setTitle:title forState:UIControlStateNormal];
        if (!index) {
            button.selected = YES;
            self.lastButton = button;
        }
    }
    [self setConfig:self.config];
}

#pragma mark - Action
- (void)itemAction:(UIButton *)sender {
    if (sender.selected) {
        //传递事件
        if (self.selected) {
            self.selected([self.contentView.subviews indexOfObject:sender]);
        }
        return;
    }
    
    //更新状态
    sender.selected = !sender.selected;
    sender.titleLabel.font = sender.selected ? self.config.itemSelectedFont : self.config.itemDefaultFont;
    self.lastButton.selected = !self.lastButton.selected;
    self.lastButton.titleLabel.font = self.lastButton.selected ? self.config.itemSelectedFont : self.config.itemDefaultFont;
    self.lastButton = sender;
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
    
    //自动偏移
    [self autoOffset:sender];
            
    //传递事件
    if (self.selected) {
        self.selected([self.contentView.subviews indexOfObject:sender]);
    }
    [self setNeedsLayout];
    [self layoutIfNeeded];
}
- (void)autoOffset:(UIButton *)sender {
    CGFloat totalButtonWidth = 0;
    for (UIButton *item in self.contentView.subviews) {
        CGFloat width = [item.titleLabel.text boundingRectWithSize:CGSizeMake(MAXFLOAT, MAXFLOAT) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:item.titleLabel.font} context:nil].size.width;
        totalButtonWidth += width;
    }
    
    ///未来的总长度
    CGFloat maxWidth = totalButtonWidth + (self.contentView.subviews.count - 1) * self.config.minItemSpace + self.config.edgeSpace * 2;
    
    if (maxWidth > self.frame.size.width && !self.config.minCountAutoOnCenter) {
        CGFloat scrollX = sender.center.x - self.frame.size.width * 0.5;
        if (scrollX < 0) {
            scrollX = 0;
        }
        if (scrollX > self.contentSize.width - self.frame.size.width) {
            scrollX = self.contentSize.width - self.frame.size.width;
        }
        [self setContentOffset:CGPointMake(scrollX, 0) animated:YES];
    }
}

@end
